import request from "@/util/requestCache";
import { Message } from "element-ui";
import {
  SyncGetCityDic,
  SyncGetRoleDic,
  SyncQuestionTypes,
} from "@/api/config";

function createLengthArray(length) {
  let options = new Array(length + 1);
  for (let i = 0; i < length + 1; i++) {
    options[i] = {
      label: i + 1,
      value: i + 1,
    };
  }
  return options;
}

export default {
  namespaced: true,
  state: {
    currentCity: [], // 当前选择的省
    currentDistrict: [], // 当前选择的市
    cityDic: [], // 城市缓存
    roleDic: [], // 权限缓存
    categoryMaxSort: 1, // 分类栏图标最大排序

    permissionList: [], // 所有角色列表

    usefulCity: [], //当前配置过的city
    usefulExhibition: [], // 当前可用的展会

    firstCategoryMaxSort: 1, //一级商品类目最大排序
    firstCategoryMaxIndexSort: 1, //一级类目最大首页排序

    firstCategoryList: [], // 当前可用的一级类目
    secondCategoryList: [], // 当前可用的二级类目

    allRoleList: [], //所有角色列表

    questionTypes: [], // 问题列表
  },
  getters: {
    cityCodMap(state) {
      function reduceFn(prev, curr) {
        prev[curr.key] = curr;
        if (curr.childs) {
          curr.childs.reduce(reduceFn, prev);
        }
        return prev;
      }
      return state.cityDic.reduce(reduceFn, {});
    },
    province(state) {
      return state.cityDic.map((dic) => {
        return {
          label: dic.value,
          value: Number(dic.key),
        };
      });
    },
    provinceAll(_, getters) {
      return [{ label: "全国", value: 0 }].concat(getters.province);
    },
    city(state) {
      return state.currentCity.map((dic) => {
        return {
          label: dic.value,
          value: Number(dic.key),
        };
      });
    },
    district(state) {
      return state.currentDistrict.map((dic) => {
        return {
          label: dic.value,
          value: Number(dic.key),
        };
      });
    },
    //
    currFirstCategoryMap(state) {
      return state.firstCategoryList.filter;
    },
    categoryList() {
      // 临时用于一级分类/二级分类复选
      return ["桌子", "椅子", "沙发", "冰箱", "茶几", "宠物"];
    },
    categoryMaxSort(state) {
      return createLengthArray(state.categoryMaxSort);
    },
    usefulCity(state) {
      return state.usefulCity
        .filter((city) => city && city.cityCode)
        .map((city) => {
          return {
            value: city.cityCode,
            label: city.city,
          };
        });
    },
    usefulExhibition(state) {
      return state.usefulExhibition.map((exhibition) => {
        return {
          value: exhibition.id,
          label: exhibition.exhibitionName,
        };
      });
    },
    firstCategoryMax(state) {
      return createLengthArray(state.firstCategoryMaxSort);
    },
    firstCategoryIndexMax(state) {
      return createLengthArray(state.firstCategoryMaxIndexSort);
    },
    firstCategoryList(state) {
      return state.firstCategoryList.map((item) => {
        return {
          label: item.categoryName,
          value: item.id,
        };
      });
    },
    secondCategoryList(state) {
      return state.secondCategoryList.map((item) => {
        return {
          label: item.categoryName,
          value: item.id,
        };
      });
    },
    permissionMap(state) {
      const permissionMap = {};
      for (let i = 0; i < state.roleDic.length; i++) {
        permissionMap[state.roleDic[i].id] = state.roleDic[i].permissionName;
      }
      return permissionMap;
    },
    permissionOptions(state) {
      return state.roleDic.map((role) => {
        return {
          label: role.permissionName,
          value: role.id,
        };
      });
    },
    permissionList(state) {
      return state.permissionList;
    },
    allRoleList(state) {
      return state.allRoleList;
    },
    questionTypes(state) {
      return state.questionTypes.map((type) => {
        return {
          label: type,
          value: type,
        };
      });
    },
    lifeMailId(state) {
      let id = null;
      state.firstCategoryList.forEach((category) => {
        if (category.categoryName === "生活商城") {
          id = category.id;
        }
      });
      return id;
    },
  },
  actions: {
    // 获取当前city 字典
    async getCityDic({ state }) {
      if (state.cityDic.length) {
        return;
      }
      const { data, error } = await SyncGetCityDic();
      if (error) {
        Message({
          type: "error",
          message: error.message || String(error),
        });
        return;
      }
      state.cityDic = data.data.bussData;
    },

    async getRoleDic({ state }) {
      if (state.roleDic.length) {
        return;
      }
      const { data, error } = await SyncGetRoleDic();
      if (error) {
        Message({
          type: "error",
          message: error.message || String(error),
        });
        return;
      }
      state.roleDic = data.data.bussData;
    },
    // 获取当前city列表
    getCity({ state }, province) {
      if (!province) {
        state.currentCity = [];
      } else {
        state.cityDic.forEach((pro) => {
          if (String(pro.key) === String(province)) {
            state.currentCity = pro.childs;
          }
        });
      }
    },
    // 获取当前district列表
    getDistrict({ state }, city) {
      if (!city) {
        state.currentDistrict = [];
      } else {
        state.currentCity.forEach((pro) => {
          if (String(pro.key) === String(city)) {
            state.currentDistrict = pro.childs;
          }
        });
      }
    },
    // 获取一级类目最大排序
    getFirstCategoryMax({ state }) {
      return new Promise((resolve, reject) => {
        request({
          url: "/admin/first/maxSort",
          method: "POST",
          data: {},
        })
          .then((data) => {
            state.firstCategoryMaxSort = data.bussData || 0;
            resolve(state.firstCategoryMaxSort + 1);
          })
          .catch((err) => {
            Message({
              type: "error",
              message: err.message || String(err),
            });
            reject();
          });
      });
    },
    // 获取一级类目首页最大排序
    getFirstCategoryIndexMax({ state }) {
      return new Promise((resolve, reject) => {
        request({
          url: "/admin/first/maxIndexSort",
          method: "POST",
          data: {},
        })
          .then((data) => {
            state.firstCategoryMaxIndexSort = data.bussData || 0;
            resolve(state.firstCategoryMaxIndexSort + 1);
          })
          .catch((err) => {
            Message({
              type: "error",
              message: err.message || String(err),
            });
            reject();
          });
      });
    },
    // 获取分类图标最大序号
    getCategoryMaxSort({ state }) {
      return new Promise((resolve, reject) => {
        request({
          url: "/admin/classified/maxSort",
          method: "POST",
          data: {},
        })
          .then((data) => {
            state.categoryMaxSort = data.bussData || 0;
            resolve(state.categoryMaxSort + 1);
          })
          .catch((err) => {
            Message({
              type: "error",
              message: err.message || String(err),
            });
            reject();
          });
      });
    },
    // 获取当前可用城市列表配置
    getUsefulCity({ state }) {
      request({
        url: "/admin/merchant/cityList",
        method: "POST",
        data: {},
      })
        .then((data) => {
          state.usefulCity = data.bussData || [];
        })
        .catch((err) => {
          Message({
            type: "error",
            message: err.message || String(err),
          });
        });
    },
    getPermissionList({ state }) {
      request({
        url: "/admin/role/getAllAppPermission",
        method: "POST",
        data: {},
      })
        .then((data) => {
          state.permissionList = data.bussData || [];
        })
        .catch((err) => {
          Message({
            type: "error",
            message: err.message || String(err),
          });
        });
    },
    // 获取当前可用的一级类目配置
    getFirstCategoryList({ state }, isShow = true) {
      let data =
        isShow === "all"
          ? {}
          : {
              isShow,
            };

      request({
        url: "/admin/first/categoryList",
        method: "POST",
        data: data,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded;",
        },
      })
        .then((data) => {
          state.firstCategoryList = data.bussData || [];
        })
        .catch((err) => {
          Message({
            type: "error",
            message: err.message || String(err),
          });
        });
    },
    // 获取当前可用的二级类目配置
    getSecondCategoryList({ state }, parentIds = []) {
      const postId =
        typeof parentIds === "number"
          ? [parentIds]
          : parentIds.map((item) => item.id);

      request({
        url: "/admin/categorySon/categoryList",
        method: "POST",
        data: {
          parentId: postId,
        },
        headers: {
          "Content-Type": "application/x-www-form-urlencoded;",
        },
      })
        .then((data) => {
          state.secondCategoryList = data.bussData || [];
        })
        .catch((err) => {
          Message({
            type: "error",
            message: err.message || String(err),
          });
        });
    },
    // 获取当前可用展会
    getUsefulExhibition({ state }, city = []) {
      const cityCodes = city.map((item) => item.id);
      request({
        url: "/admin/exhibition/exhibitionList",
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded;",
        },
        data: {
          cityCodes,
        },
      })
        .then((data) => {
          state.usefulExhibition = data.bussData || [];
        })
        .catch((err) => {
          Message({
            type: "error",
            message: err.message || String(err),
          });
        });
    },
    getAllExhibition({ dispatch }) {
      request({
        url: "/admin/merchant/cityList",
        method: "POST",
        data: {},
      }).then((data) => {
        let city = data.bussData.map((item) => ({
          ...item,
          id: item.cityCode,
        }));
        dispatch("getUsefulExhibition", city);
      });
    },
    getAllRole({ state }) {
      request(
        {
          url: "/admin/role/findAppRoleByPage",
          method: "POST",
          data: {
            pageIndex: 1,
            pageSize: 10000,
          },
        },
        60
      ).then((data) => {
        state.allRoleList = data.bussData.map((role) => {
          return {
            label: role.roleName,
            value: role.id,
          };
        });
      });
    },
    async getQuestionTypes({ state }) {
      const { data, error } = await SyncQuestionTypes();
      if (error) {
        Message({
          type: "error",
          message: error.message || String(error),
        });
        return;
      }
      const questionTypes = [];
      data.data.bussData.forEach((item) => {
        if (questionTypes.includes(item.questionType)) return;
        questionTypes.push(item.questionType);
      });
      state.questionTypes = questionTypes;
    },
  },
};
